<script setup>
import baseModel from "@/components/baseModel/baseModel.vue";
import {
  computed,
  nextTick,
  onMounted,
  ref,
  defineProps,
  defineEmits,
  watch,
} from "vue";
import request from "@/common/utils/request";
import AddAudioLoding from "./componens/AddAudioLoding.vue";
import { SwapOutlined } from "@ant-design/icons-vue";

// 绘制视频帧函数
import {
  splitVideo,
  splitAndDrawVideoFrames,
} from "@/views/shotstack/MuseMixedCut/utools/index.js";
import { message } from "ant-design-vue";
// import { watch } from "less";
const newStateLoading = ref(false);

const props = defineProps({
  start_upload_data: {
    type: Object,
  },
  closeedLoading: {
    type: Boolean,
  },
});
const dialog = ref(null);
const resolveArr = ref([]);
// 视频链接
const audioUrl = ref("");
const showModal = (data) => {
  audioUrl.value = data;
  audioUrl.value.url = data.url + "?v=" + new Date().valueOf();
  audioDuration.value = data.material_duration;

  // 初始赋值
  data?.containerLeft && (containerLeft.value = data.containerLeft);
  data?.containerWidth && (containerWidth.value = data.containerWidth);

  dialog.value.showModal();

  newStateLoading.value = false;
  nextTick(() => {
    initCanvas();
    // 绘制视频帧
    splitAndDrawVideoFrames({
      videoId: "#videoElement",
      canvasId: "#canvasElement",
      audioUrl: audioUrl.value.url,
      maxFrameHeight: 36, // 假设我们希望每个帧的最大高度
      canvasWidth: 850, // Canvas的总宽度
    });
  });
};

// 调用重新绘制函数
const initCanvasFn = (data) => {
  audioUrl.value = data;
  audioUrl.value.url = data.url + "?v=" + new Date().valueOf();
  audioDuration.value = data.material_duration;
  resetContainer();
  nextTick(() => {
    initCanvas();
    // 绘制视频帧
    splitAndDrawVideoFrames({
      videoId: "#videoElement",
      canvasId: "#canvasElement",
      audioUrl: audioUrl.value.url,
      maxFrameHeight: 36, // 假设我们希望每个帧的最大高度
      canvasWidth: 850, // Canvas的总宽度
    });
  });
};

// 重置抓手数据
const resetContainer = () => {
  containerWidth.value = 850;
  containerLeft.value = 0;
};

// 等待弹窗取消轮询
const AudioLodingCancel = () => {
  emit("cancelLoding");
  saveLoading.value = false;
};
const closeModal = () => {
  resetContainer();
  saveLoading.value = false;
  emit("cancelLoding");
  dialog.value.closeModal();
};

const paramsData = ref({});
const TaskData = ref({});
const emit = defineEmits([
  "update:list",
  "audioLoading",
  "ReAdd",
  "cancelLoding",
]);
const addaudioLoading = ref(null);
const saveLoading = ref(false); //音频识别的loading
// 更新保存按钮的loading状态
const updateSaveLoading = (status) => {
  saveLoading.value = status;
};
// 保存视频
const save = () => {
  // 打开loading效果
  addaudioLoading.value.showModal();
  // 1. 判断音频是否切割
  if (
    calculateTimeRange.value.startTime !== 0 ||
    calculateTimeRange.value.endTime !==
    props.start_upload_data.material_duration
  ) {
    // 1. 将毫秒 转成 秒
    paramsData.value.start_time = +(
      calculateTimeRange.value.startTime / 1000
    ).toFixed(0);
    paramsData.value.end_time = +(
      calculateTimeRange.value.endTime / 1000
    ).toFixed(0);
  } else if (
    calculateTimeRange.value.startTime == 0 &&
    calculateTimeRange.value.endTime ==
    props.start_upload_data.material_duration
  ) {
    paramsData.value.start_time = 0;
    paramsData.value.end_time = 0;
  }

  //TODO 测试混剪音频的时候设置的值, 结束需注释
  // paramsData.value.start_time = 0
  // paramsData.value.end_time = 0
  paramsData.value.audio_url = props.start_upload_data.url;
  paramsData.value.material_id = props.start_upload_data.id;
  updateSaveLoading(true);
  request
    .post("/work_ai", "/user/shotstack/parseAudioToTxtByTime", paramsData.value)
    .then((res) => {
      if (res?.code && res.code != 1000) {
        addaudioLoading.value.closeDrawer();
        updateSaveLoading(false);
        throw new Error("音频解析失败!");
      }
      TaskData.value.id = res.result.Data.TaskId;
      TaskData.value.start_time = calculateTimeRange.value.startTime;
      TaskData.value.end_time = calculateTimeRange.value.endTime;
      TaskData.value.url = res.result.audio_url;
      emit("update", TaskData.value);
    })
    .catch((err) => {
      updateSaveLoading(false);
      newStateLoading.value = true;

      message.error("音频解析失败!");
    });
};
const reset = () => {
  addaudioLoading.value.closeDrawer();
  closeModal();
  updateSaveLoading(false);
};

// 绘制canvas刻度
const initCanvas = () => {
  return
  // debugger
  // 获取 canvas 元素及其上下文
  var canvas = document.getElementById("rulerCanvas");
  var ctx = canvas.getContext("2d");
  // 设定 canvas 的宽度和高度以铺满容器
  canvas.width = canvas.offsetWidth;
  canvas.height = 30; // 设定一个固定的高度
  var width = canvas.width;
  var height = canvas.height;
  // 刻度数量，更多刻度会使得间隔更短
  var totalTicks = 80;
  // 时间标签数量
  var timeStamps = 8;
  // 设定每个刻度的间隔
  var tickInterval = width / totalTicks;
  var timeStampInterval = width / timeStamps;

  // 画上方的线条
  ctx.beginPath();
  ctx.moveTo(0, 1);
  ctx.lineTo(width, 1);

  // 绘制刻度
  for (var i = 0; i <= totalTicks; i++) {
    ctx.moveTo(tickInterval * i, 0);
    ctx.lineTo(tickInterval * i, height / 5); // 刻度的长度为canvas的高度的四分之一
  }

  // 时间标签
  for (var j = 0; j < timeStamps; j++) {
    var xPosition = timeStampInterval * j + timeStampInterval / 2; // 将时间标签居中放置在间隔位置

    // 添加时间文本，这里只是示例，你需要根据实际情况来格式化时间
    var text = `时间${j + 1}`;
    var textWidth = ctx.measureText(text).width;
    var textX = xPosition - textWidth / 2; // 计算文本x位置
    var textY = height / 8 + 20; // 调整文本y位置，留出足够空间以防止文字挤压
    ctx.fillStyle = "#7a7a7a"; // 文字颜色
    // 绘制文本
    ctx.fillText(text, textX, textY);
  }

  // 设置线条样式
  ctx.strokeStyle = "#7a7a7a"; // 黑色线条
  ctx.lineWidth = 1; // 线宽为1px
  ctx.stroke();

  // 结束绘制路径
  ctx.closePath();
};

// 初始容器宽度和拖拽状态
const containerWidth = ref(850);
// 当前元素定位的左侧
const containerLeft = ref(0);
let isResizing = false;
let startWidth = 0;
let startLeft = 0;
let startX = 0;
const handelMousedown = (event, direction) => {
  // 防止选中文本
  event.preventDefault();
  isResizing = true;
  startX = event.clientX;
  startWidth = containerWidth.value;
  startLeft = containerLeft.value;

  const maxWidth = 850; // 假设这是父元素的最大宽度

  const doResize = (moveEvent) => {
    if (!isResizing) return;
    const dx = moveEvent.clientX - startX;

    if (direction === "right") {
      let newWidth = startWidth + dx;
      // 确保新宽度不会小于最小宽度
      const minWidth = 50;
      // 如果新宽度加上左侧定位超过最大宽度，则限制它
      if (newWidth + startLeft > maxWidth) {
        newWidth = maxWidth - startLeft;
      } else if (newWidth < minWidth) {
        // 如果新宽度小于最小宽度，则设置为最小宽度
        newWidth = minWidth;
      }
      containerWidth.value = newWidth;
    } else {
      // 左侧拖拽逻辑
      const newWidth = startWidth - dx;
      if (newWidth > 50 && startLeft + dx >= 0) {
        containerWidth.value = newWidth;
        containerLeft.value = startLeft + dx;
      }
    }

    audioUrl.value.containerLeft = containerLeft.value;
    audioUrl.value.containerWidth = containerWidth.value;
  };

  const stopResize = () => {
    isResizing = false;
    window.removeEventListener("mousemove", doResize);
    window.removeEventListener("mouseup", stopResize);
  };

  // 监听鼠标移动和松开事件
  window.addEventListener("mousemove", doResize);
  window.addEventListener("mouseup", stopResize);
};

// 计算框选的范围
// 假设的视频时长
const audioDuration = ref(0); // 模拟的视频时长变量，20s
const calculateTimeRange = computed(() => {
  const pixelsPerSecond = audioDuration.value / 850;
  const startTime = containerLeft.value * pixelsPerSecond;
  const endTime =
    (containerLeft.value + containerWidth.value) * pixelsPerSecond;
  return { startTime, endTime };
});

// 重新- 替换音频
const ReAdd = () => {
  emit("ReAdd", audioUrl.value);
};

// 导入 二选一
const choose_upload = ref("1");

const closeLodingDialog = () => {
  addaudioLoading.value.closeDrawer();
};

watch(
  () => props.closeedLoading,
  (val) => {
    if (val == true) {
      newStateLoading.value = true;
      setTimeout(() => {
        closeModal();
      }, 1000);
    }
  }
);

defineExpose({
  showModal,
  closeModal,
  reset,
  initCanvasFn,
  closeLodingDialog,
  updateSaveLoading,
});
</script>

<template>
  <div class="ViewVideoModel" style="z-index: 990 !important">
    <baseModel ref="dialog" @isClose="reset" :contentWidth="'900px'" :maskClosable="false" :destroyOnClose="true"
      :zIndex="1001">
      <template #title>
        <div class="title_box">
          <span>请选取要使用的音频范围</span>
        </div>
      </template>
      <template #content>
        <div class="content">
          <div class="video_box">
            <div class="video_box_left">
              <!-- 播放按钮 -->
              <div class="video_box_left_one">
                <cu-icon type="icon-yinle2" style="font-size: 25px"></cu-icon>
              </div>

              <div class="video_box_left_two">
                <div class="video_box_left_two_top">
                  {{ props.start_upload_data.name }}
                </div>
                <div class="video_box_left_two_bottom">
                  <audio style="width: 655px; height: 25px" :src="props.start_upload_data.url" controls></audio>
                </div>
              </div>
            </div>
            <div class="video_box_right">
              <a-popover trigger="hover">
                <template #content>
                  <a-radio-group v-model:value="choose_upload" name="radioGroup">
                    <a-radio value="1">素材库导入</a-radio>
                    <!-- <a-radio value="2">本地上传</a-radio> -->

                    <div class="video_popover_btn">
                      <a-button class="popver_left_btn" size="small">
                        取消
                      </a-button>
                      <a-button size="small" type="primary" @click="ReAdd">
                        确定
                      </a-button>
                    </div>
                  </a-radio-group>
                </template>
                <a-button size="small">
                  替换
                  <SwapOutlined />
                </a-button>
              </a-popover>
            </div>
          </div>
          <!-- <div class="canvasBox">
            <canvas
              id="rulerCanvas"
              height="20"
              style="width: 100%; height: 30px"
            ></canvas>
          </div> -->
          <!-- 图片容器 -->
          <div class="imgBox">
            <canvas id="canvasElement" ref="canvasElement" style="height: 100%; width: 100%"></canvas>
            <!-- 抓手容器 -->
            <div class="handles" :style="{
              width: containerWidth + 'px',
              left: containerLeft + 'px',
            }">
              <div class="handle_left handle" @mousedown="handelMousedown($event, 'left')"></div>
              <div class="handle_right handle" @mousedown="handelMousedown($event, 'right')"></div>
            </div>
            <!-- <div class="img_item_box" v-for="item in resolveArr" :key="item.time">
                            <img :src="item.src" alt="">
                        </div> -->
          </div>
        </div>
      </template>
      <template #footer>
        <div class="bottom">
          <a-button class="btn" key="back" @click="reset" style="margin-right: 10px">取消</a-button>
          <a-button class="btn" key="submit" type="primary" :loading="saveLoading" :disabled="disableSubmit"
            @click="save">音频识别</a-button>
        </div>
      </template>
    </baseModel>
    <!-- 这个canvas元素用于绘制视频帧 -->
    <!-- <canvas id="canvasElement" ref="canvasElement" style="display: none;"></canvas> -->
    <!-- 这个video元素用于加载和控制视频 "https://cos.kuaijingai.com/upload/work_ai/20240305/65e6f4034cd8937599.mp4" -->
    <video id="videoElement" ref="videoElement" style="display: none" crossOrigin="anonymous" controls preload="auto"
      src="" />
    <AddAudioLoding :newStateLoading="newStateLoading" ref="addaudioLoading" @cancel="AudioLodingCancel">
    </AddAudioLoding>
  </div>
</template>

<style lang="less" scoped>
.title_box {
  span {
    color: #1c1f23;
    font-size: 18px;
  }
}

.bottom {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .btn {
    border-radius: 4px;
    overflow: hidden;
  }
}

.content {
  .video_box {
    width: 840px;
    padding-left: 14px;
    border: 1px solid #e1e2e8;
    border-radius: 7px;
    margin-bottom: 40px;
    display: flex;
    height: 86px;
    line-height: 86px;

    .video_box_left {
      display: flex;
      width: 90%;
      border-right: 1px solid #e1e2e8;
      align-items: center;

      .video_box_left_one {
        margin-right: 15px;
        width: 56px;
        height: 56px;
        background-color: #bec0c2;
        border-radius: 3px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .video_box_left_two {
        height: 84px;

        .video_box_left_two_top {
          width: 560px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          height: 42px;
          height: 42px;
          line-height: 48px;
          font-size: 14px;
          font-weight: 600;
        }

        .video_box_left_two_bottom {
          height: 42px;
          height: 42px;
          line-height: 42px;
        }
      }
    }

    .video_box_right {
      width: 10%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .imgBox {
    height: 36px;
    display: flex;
    justify-content: flex-start;
    position: relative;

    // 抓手
    .handles {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
      // width: 100%;
      border: 2px solid #1664ff;
      background: rgba(190, 220, 255, 0.6);

      .handle {
        background: #1664ff;
        height: inherit;
        position: absolute;
        width: 12px;
        height: calc(100% + 4px);
        cursor: ew-resize;
      }

      .handle_left {
        left: -14px;
        top: -2px;
        border-radius: 6px 0px 0px 6px;
      }

      .handle_right {
        left: calc(100% + 2px);
        top: -2px;
        border-radius: 0px 6px 6px 0px;
      }
    }

    .img_item_box {
      display: inline-block;
      // height: 100%;
      flex: 1;
      display: flex;

      img {
        flex: 1;
        object-fit: cover;
      }
    }
  }

  .canvasBox {
    width: 100%;
  }
}

.video_popover_btn {
  margin: 20px 0 0 100px;

  .popver_left_btn {
    margin-right: 5px;
  }
}
</style>
